import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


img_dir = '../../../../../large_data/CV2/lesson/Day07'
img_name = 'football_ball.jpg'
temp_path = os.path.join(img_dir, img_name)

img_dir = '../../../../../large_data/pic'
# img_name = 'DSC05039.JPG'
# img_name = 'DSC05022_1.JPG'
# img_name = 'dog.jpg'
# img_name = 'dog_bird.jpg'
img_name = 'football.jpg'
# img_name = 'messi5.jpg'
img_path = os.path.join(img_dir, img_name)

spr = 2
spc = 3
spn = 0
plt.figure(figsize=[9, 6])

sep('load')
img = cv.imread(img_path, cv.IMREAD_COLOR)
print('original shape', img.shape)
H, W, CH = img.shape
H2 = H // 2
W2 = W // 2
my_show_img(img, 'original', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))
img_ = img.copy()

temp = cv.imread(temp_path, cv.IMREAD_COLOR)
print('temp shape', temp.shape)
HT, WT, CHT = temp.shape
my_show_img(temp, 'temp', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('do match')
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY).astype(np.float32) / 255.
temp_gray = cv.cvtColor(temp, cv.COLOR_BGR2GRAY).astype(np.float32) / 255.
res = convolution_numpy_acc(img_gray, temp_gray)
my_show_img(res, 'res', cmap='gray')

sep('seek min max')
minVal, maxVal, minLoc, maxLoc = cv.minMaxLoc(res)
print(minVal, maxVal, minLoc, maxLoc)

sep('tick')
cv.rectangle(img, maxLoc, (maxLoc[0] + WT, maxLoc[1] + HT), (0, 0, 255), 2)
my_show_img(img, 'original', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('do match with centering')
print('means: ', img_gray.mean(), temp_gray.mean())
img_gray -= img_gray.mean()
temp_gray -= temp_gray.mean()
res = convolution_numpy_acc(img_gray, temp_gray)
my_show_img(res, 'res', cmap='gray')

sep('seek min max')
minVal, maxVal, minLoc, maxLoc = cv.minMaxLoc(res)
print(minVal, maxVal, minLoc, maxLoc)

sep('tick')
img = img_.copy()
cv.rectangle(img, maxLoc, (maxLoc[0] + WT, maxLoc[1] + HT), (0, 0, 255), 2)
my_show_img(img, 'original', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))
